package com.example.cdctest.controller;

import com.example.cdctest.pojo.Config;
import com.example.cdctest.pojo.Notice;
import com.example.cdctest.pojo.UserInfo;
import com.example.cdctest.service.NoticeService;
import com.example.cdctest.service.UserInfoService;
import com.example.cdctest.util.MailUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;


@Controller
@RequestMapping("/services")
public class UserInfoController {
    @Resource
    private UserInfoService userInfoService;

    @Resource
    private NoticeService noticeService;

    @RequestMapping("index")
    public ModelAndView login(HttpServletRequest request) {
        ModelAndView modelAndView=new ModelAndView();
        Integer noticeCount=1;
        ServletContext servletContext=request.getSession().getServletContext();
        List<Config> configList=(List<Config>) servletContext.getAttribute("configs");
        for (Config config : configList) {
            if("web_notice_count".equals(config.getKey())){
                noticeCount=Integer.parseInt(config.getValue());
            }
        }
       modelAndView.addObject("noticeList",noticeService.findAllServicesNotice(noticeCount));
        modelAndView.setViewName("/services/index");
        return modelAndView;
    }

    //根据公告信息的Id,查出该Id下的公告信息
    @RequestMapping("getNoticeById")
    public ModelAndView getNoticeById(Integer noticeId){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("notice",noticeService.findById(noticeId));
        modelAndView.setViewName("/services/notice-list");
        return modelAndView;
    }

    @RequestMapping("user_info")
    public UserInfo user_info(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("loginUser");
        String email=userInfo.getEmail();
        if(userInfo.getPic()==null){userInfo.setPic("   ");}
        if(userInfo.getUserName()==null){userInfo.setUserName(" ");}
        if(userInfo.getSex()==null){userInfo.setSex("   ");}
        if(userInfo.getPhone()==null){userInfo.setPhone("   ");}
        if(userInfo.getEmail()==null) {userInfo.setEmail("  ");}
        return userInfoService.selectUserByEmail(email);
    }
    @RequestMapping("update_user_info")
    public UserInfo update_user_info(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("loginUser");
        String email=userInfo.getEmail();
        return userInfoService.selectUserByEmail(email);
    }
    @RequestMapping("update_user_info_form")
    public String update_user_info_form(UserInfo userInfo, HttpSession session, MultipartFile file, HttpServletRequest request) {
        UserInfo user = (UserInfo) session.getAttribute("loginUser");
        if(!file.isEmpty()) {
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            if (!",jpg,jpeg,png,gif,".contains("," + ext + ",")) {
                return "redirect:/services/update_user_info";
            }
            String fileName = UUID.randomUUID() + "." + ext;
            File directory = new File("src/main/webapp/user/picture");
            String path=null;
            try {
                path = directory.getCanonicalPath();
            } catch (IOException e) {
                e.printStackTrace();
            }
            File file1 = new File(path, fileName);
            try {
                file.transferTo(file1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            userInfo.setPic(fileName);
        }
        if(userInfo.getSex().equals("1"))
        {
            userInfo.setSex("男");
        }else {userInfo.setSex("女");}
        userInfo.setEmail(user.getEmail());
        if(userInfo.getUserName().equals("")) {
            userInfo.setUserName(user.getUserName());
        }else{
            user.setUserName(userInfo.getUserName());
        }
        if(userInfo.getSex().equals("")){
            userInfo.setSex(user.getSex());
        }else{
            user.setSex(userInfo.getSex());
        }
        if(userInfo.getPic()==null){
            userInfo.setPic(user.getPic());
        }else{
            user.setPic(userInfo.getPic());
        }
        if(userInfo.getPhone().equals("")){
            userInfo.setPhone(user.getPhone());
        }else{
            user.setPhone(userInfo.getPhone());
        }
        if(userInfo.getArea().equals("")){
            userInfo.setArea(user.getArea());
        }else{
            user.setArea(userInfo.getArea());
        }
        if(userInfo.getBirthday()==null){
            userInfo.setBirthday(user.getBirthday());
        }else{
            user.setBirthday(userInfo.getBirthday());
        }
        userInfoService.updateUserInfo(userInfo);
        return "redirect:/services/user_info";
    }
    @RequestMapping("update_password")
    public UserInfo update_password(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("loginUser");
        String email=userInfo.getEmail();
        return userInfoService.selectUserByEmail(email);
    }
    @RequestMapping("update_password_form")
    public String update_password_form(UserInfo userInfo,HttpSession session) {
        UserInfo user = (UserInfo) session.getAttribute("loginUser");
        userInfo.setEmail(user.getEmail());
        userInfoService.update(userInfo);
        return "/services/index";
    }
    @RequestMapping("my_collection")
    public UserInfo my_collection(HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("loginUser");
        String email=userInfo.getEmail();
        return userInfoService.selectUserByEmail(email);
    }
    @RequestMapping("ForgetPassword")
    public void forgetPassword(){
    }
    @RequestMapping("ForgetPassword2")
    public void forgetPassword2(){
    }
    @RequestMapping("goForgetPassword")
    public ModelAndView ForgetPassword(String email, HttpSession session, String checkbox, HttpServletResponse response) {
        UserInfo user = new UserInfo();
        user.setEmail(email);
        UserInfo loginUser = userInfoService.login(user);
        ModelAndView modelAndView = new ModelAndView();
        if (loginUser != null) {
            modelAndView.setViewName("/services/login");
            return modelAndView;
        } else {
            String err = "0";
            modelAndView.addObject("err", err);
            modelAndView.setViewName("/services/ForgetPassword");
            return modelAndView;
        }
    }
    //用户忘记密码,验证邮箱账号和验证码,正确到输入密码的页面
    @RequestMapping("isForgetCode")
    public ModelAndView isForgetCode(String emailCode,String email,HttpSession session) throws IOException {
        ModelAndView modelAndView=new ModelAndView();
        String code = (String)session.getAttribute("code");
        if(emailCode.equalsIgnoreCase(code)){
            modelAndView.addObject("email",email);
            modelAndView.setViewName("/services/ForgetPassword2");
            return modelAndView;
        }else {
            modelAndView.setViewName("/services/ForgetPassword");
            return modelAndView;
        }
    }
//--------------------------------------------------------------------------------
    @RequestMapping("isForgetChange")
    public ModelAndView isForgetChange(String newpassword, String Confirmpassword,String email,HttpSession session) throws IOException {
        ModelAndView modelAndView=new ModelAndView();
        if (newpassword.equals(Confirmpassword))
{
    UserInfo user = new UserInfo();
    user.setEmail(email);
    user.setPassword(newpassword);
    userInfoService.update(user);
    modelAndView.setViewName("/services/login");
    return modelAndView;
}
else {
    modelAndView.setViewName("/services/ForgetPassword2");
    return modelAndView;
}
    }

     @RequestMapping("regist")
    public String regist(UserInfo userInfo)
        {
        userInfoService.insert(userInfo);
        return "/services/goLogin";
    }

    @RequestMapping("isEmail")
    @ResponseBody
    public String isEmail(UserInfo userInfo) {
        UserInfo temp = userInfoService.isEmail(userInfo);
        if (temp == null) {
            return "0";
        } else {
            return "1";
        }
    }
    //用户忘记密码发送验证码
    @RequestMapping("sendUpdateEmail")
    public void sendUpdatePassEmail(UserInfo userInfo, HttpSession session,HttpServletResponse response) throws IOException {
        UserInfo use = userInfoService.isEmail(userInfo);
        if (use != null) {
            String code = MailUtil.getMailUtil().createFoursRandom();
            try {
                MailUtil.getMailUtil().sendMail("验证码", MailUtil.getMailUtil().getMailContent(code), userInfo.getEmail());
                session.setAttribute("code",code);
            }catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            response.getWriter().print("0");
        }
    }
    @RequestMapping("sendEmail")
    public void sendEmail(UserInfo userInfo, HttpSession session,HttpServletResponse response) throws IOException {
        UserInfo user = (UserInfo) session.getAttribute("loginUser");
        if(user == null)
        {
            UserInfo temp = userInfoService.isEmail(userInfo);
            if (temp == null) {
                String code = MailUtil.getMailUtil().createFoursRandom();
                try {
                    MailUtil.getMailUtil().sendMail("验证码", MailUtil.getMailUtil().getMailContent(code), userInfo.getEmail());
                    session.setAttribute("code",code);
                }catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                response.getWriter().print("0");
            }
        }else {
            String code = MailUtil.getMailUtil().createFoursRandom();
            try {
                MailUtil.getMailUtil().sendMail("验证码", MailUtil.getMailUtil().getMailContent(code), user.getEmail());
                session.setAttribute("code",code);
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("isEmailCode")
    public void isEmailCode(String emailCode,HttpSession session,HttpServletResponse response) throws IOException {
        String code = (String)session.getAttribute("code");
        if(emailCode.equalsIgnoreCase(code)){
            response.getWriter().print("0");
        }else {
            response.getWriter().print("1");
        }
    }

    //申请为内测用户
    @RequestMapping("update-vip-user")
    @ResponseBody
    public String updateVipUser(Integer id){
        userInfoService.updateVipUser(id);
        return "1";
    }
}
